/*
	The MIT License

	Copyright (c) 2010 IFMO/GameDev Studio

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.
*/
// d3d_main.cpp - 

#include "d3d_local.h"
#include "fr_local.h"
#include "dbg_scene.h"


//DLL_EXPORT ICoreObject *CreateRenderSystem(void)
//{
//	return new ED3DRenderSystem();
//}
//

ED3DRenderSystem *ED3DRenderSystem::self	=	NULL;

/*-----------------------------------------------------------------------------
	Main stuff :	
-----------------------------------------------------------------------------*/

//
//	ED3DRenderSystem::ED3DRenderSystem
//
ED3DRenderSystem::ED3DRenderSystem()
{
	self			=	this;
	need_screenshot	=	false;
	
	LOG_SPLIT("Direct3D rendering system initialization");
	
	//shell->AddCommand("listDisplayModes",	(EShellCmd_f)ListDisplayModes_f,	this);
	//shell->AddCommand("screenShot",			(EShellCmd_f)ScreenShot_f,			this);
	
	CONFIG_REGISTER_VAR( d3d_wireframe, false );

	//
	//	Init Display and Direct3D :
	//	
	InitDisplay();
	InitDirect3D();
	
	CheckDeviceFallbacks();
	
	HRCALL(d3ddev->GetRenderTarget(0, &default_color_surf));
	HRCALL(d3ddev->GetDepthStencilSurface(&default_depth_surf));

	//	
	//	Init rendering subsystems :
	//
	draw2d	=	new ED3DDraw2D(this);
	txm		=	new ERSTextureManager(this);
	rtm		=	new ERSRTManager(this);
	mss		=	new ERSMeshSystem(this);

	InitRSAPI();
	
	LOG_SPLIT("");
}


//
//	ED3DRenderSystem::~ED3DRenderSystem
//
ED3DRenderSystem::~ED3DRenderSystem(void)
{
	LOG_SPLIT("Direct3D rendering system shutting down");
	
	mss			=	NULL;
	rtm			=	NULL;	
	txm			=	NULL;
	draw2d		=	NULL;
	
	SAFE_RELEASE(default_color_surf);
	SAFE_RELEASE(default_depth_surf);
	
	ShutdownDirect3D();
	ShutdownDisplay();
	
	LOG_SPLIT("");
}



void ED3DRenderSystem::InstallForward( void )	{	}
void ED3DRenderSystem::InstallDeferred( void )	{	}
void ED3DRenderSystem::Uninstall( void )		{	}

//
//	ED3DRenderSystem::GetTextureSize
//
void ED3DRenderSystem::GetTextureSize( const EString tex_name, uint &w, uint &h )
{
	IPxTexture	tex	=	txm->RegisterTexture(tex_name);
	w	=	tex->GetWidth();
	h	=	tex->GetHeight();
}

/*-----------------------------------------------------------------------------
	Resource registering stuff :
-----------------------------------------------------------------------------*/

class	ED3DInclude : public ID3DXInclude {
	public:
						ED3DInclude		( void );
						~ED3DInclude	( void );
		STDMETHOD(Open) 	( D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes );
		STDMETHOD(Close)	( LPCVOID pData );
	protected:
	};	
		

ED3DInclude::ED3DInclude( void )	{	}
ED3DInclude::~ED3DInclude( void )	{	}


HRESULT ED3DInclude::Open( D3DXINCLUDE_TYPE IncludeType, LPCSTR pFileName, LPCVOID pParentData, LPCVOID *ppData, UINT *pBytes )
{
	try {

		IPxFile	 f;

		if ( fs()->FileExists(pFileName) ) {
			f	=	fs()->FileOpen(pFileName, FS_OPEN_READ);
		} else {
			f	=	fs()->FileOpen(va("shaders/%s", pFileName), FS_OPEN_READ);
		}
	
		uint	sz	=	f->Size();
		LPCVOID		data	=	malloc( sz );
		f->Read(const_cast<void*>(data), sz);
		
		*pBytes	=	sz;
		*ppData	=	data;
		
		return S_OK;
		
	} catch (exception &e) {
		return S_FALSE;
	}
}


HRESULT ED3DInclude::Close( LPCVOID pData )
{
	free(const_cast<void*>(pData));
	return S_OK;
}



static void LogFXCompileMessage( bool is_error, string &str )
{
	uint n0 = 0;
	uint n1 = str.find('\n', n0);
	
	do {		
		string s = str.substr(n0, n1-n0);
		n0 = n1+1;
		n1 = str.find('\n', n0);
		
		if (is_error) {
			LOG_ERROR("%s", s.c_str());
		} else {
			LOG_WARNING("%s", s.c_str());
		}
		
	} while (n1!=string::npos);
}


//
//	ED3DRenderSystem::CompileEffect
//
ID3DXEffect *ED3DRenderSystem::CompileEffect( const char *path )
{
	ID3DXEffect	*effect = NULL;
	
	ED3DInclude	include;

	LOGF("compiling : %s", path);
	
	ID3DXBuffer	*errors = NULL;
	uint flags = 0;//D3DXFX_NOT_CLONEABLE;
	
	EString	path_alt = fs()->ResolvePath( path );
	
	HRESULT hr = D3DXCreateEffectFromFile( d3ddev, path_alt.CStr(), NULL, &include, flags, NULL, &effect, &errors );
	
	if (FAILED(hr)) {
	
		effect = NULL;
		
		if (errors) {
			string msg = (char*)errors->GetBufferPointer();
			LogFXCompileMessage(true, msg);
		} else {
			ASSERT(0);
			LOG_ERROR("file not found: %s", path);
		}
		
	} else if (errors) {
		string msg = (char*)errors->GetBufferPointer();
		LogFXCompileMessage(true, msg);
	}
	
	return effect;
}


//
//	ED3DRenderSystem::DrawFSQuad
//
void ED3DRenderSystem::DrawFSQuad( void )
{
	struct vertex2d_hw_s {
			float	 x, y, z;
			uint32_t color;
			float	 u, v;
		};

	vertex2d_hw_s quad[4];
	uint color4b = 0xFFFFFFFF;

	quad[0].x = -1;	quad[0].y = -1;	quad[0].z = 0.5;
	quad[0].u =  0; quad[0].v =  1; quad[0].color = color4b;

	quad[1].x =  1;	quad[1].y = -1;	quad[1].z = 0.5;
	quad[1].u =  1; quad[1].v =  1; quad[1].color = color4b;

	quad[2].x =  1;	quad[2].y =  1;	quad[2].z = 0.5;
	quad[2].u =  1; quad[2].v =  0; quad[2].color = color4b;

	quad[3].x = -1;	quad[3].y =  1;	quad[3].z = 0.5;
	quad[3].u =  0; quad[3].v =  0; quad[3].color = color4b;
	
	HRCALL( d3ddev->SetFVF( D3DFVF_XYZ|D3DFVF_DIFFUSE|D3DFVF_TEX1 ) );
	
	HRCALL( d3ddev->DrawPrimitiveUP(D3DPT_TRIANGLEFAN, 2, &quad, sizeof(vertex2d_hw_s)) );
}


/*-----------------------------------------------------------------------------
	Frame rendering stuff
-----------------------------------------------------------------------------*/

//
//	ED3DRenderSystem::BeginFrame
//
bool ED3DRenderSystem::BeginFrame(void)
{
	if (!RestoreDevice()) {
		return false;
	}

    HRCALL( d3ddev->BeginScene() );

	ResetDeviceState();
	
	return true;
}


//
//	ED3DRenderSystem::RestoreDevice
//
bool ED3DRenderSystem::RestoreDevice( void )
{
	HRESULT hr      =       d3ddev->TestCooperativeLevel();

	if (SUCCEEDED(hr)) {
		return true;
	}

	if (hr==D3DERR_DEVICELOST) {
		LOG_WARNING("TestCooperativeLevel() : D3DERR_DEVICELOST");
		System()->Sleep(500);
		return false;

	} else if (hr==D3DERR_DEVICENOTRESET) {
		LOGF("TestCooperativeLevel() : D3DERR_DEVICENOTRESET");
		d3ddev->Reset( &d3dpp );

		//
		//	restore resources :
		//
		//ReleaseTextures();



		LOGF("Device has been restored");
		return true;

	} else {
		FATAL( "TestCooperativeLevel() failed" );
		return false;
	}
}


//
//	ED3DRenderSystem::RenderFrame
//
void ED3DRenderSystem::RenderFrame( void )
{
	ResetDeviceState();
	if (scene) {
		scene->RenderScene();
	}

	if (fr_scene) {
		fr_scene->RenderScene();
	}
	
	if (dbg_scene) {
		dbg_scene->RenderScene();
	}
	ResetDeviceState();
}


//
//	ED3DRenderSystem::EndFrame
//
void ED3DRenderSystem::EndFrame(void)
{
	ScreenShot();
	
	HRCALL( d3ddev->EndScene() );
	
	HRESULT	hr	=	d3ddev->Present( NULL, NULL, NULL, NULL );
	
	if (hr==D3DERR_DEVICELOST) {
		LOG_WARNING("IDirect3DDevice9::Present() failed : D3DERR_DEVICELOST");
		return;
	}
    HRCALL( hr );
}


